﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml;

// Entry of Xml data file
public class XmlEntry {
	private Dictionary<string, string> data = new Dictionary<string, string>();
	
	public void set(string key, string value) {
		data.Add(key, value);
	}
	
	public string get(string name) {
		string value;
		if (data.TryGetValue(name, out value))
			return value;
		else
			return "";
	}
	
	public int getAsInt(string name) {
		string value;
		if (data.TryGetValue(name, out value))
			return int.Parse(value);
		else
			return 0;
	}
	
	public float getAsFloat(string name) {
		string value;
		if (data.TryGetValue(name, out value))
			return float.Parse(value);
		else
			return 0.0f;
	}
}

// A xml data file indexed by key string
public class XmlDataBase {
	public TextAsset asset;
	public Dictionary<string, XmlEntry> entryMap;
	
	public XmlEntry find(string key) {
		XmlEntry entry;
		if (entryMap.TryGetValue(key, out entry)) {
			return entry;
		}
		return null;
	}
	
	public void Load() {
		//TODO- configure value for record, key
		entryMap = new Dictionary<string, XmlEntry>();
		XmlDocument xmlDoc = new XmlDocument();
		xmlDoc.LoadXml( asset.text ); //load the file
		XmlNodeList xmlData = xmlDoc.GetElementsByTagName("data");
		foreach (XmlNode data in xmlData)
		{
			XmlEntry entry = new XmlEntry();
			foreach (XmlNode attr in data.Attributes) {
				//Debug.Log("XmlDataLoader.Load("+ asset.name +") : " + attr.Name + "=" + attr.Value);
				if (attr.Name == "key") entryMap.Add(attr.Value, entry);
				entry.set(attr.Name, attr.Value);
			}
		}
	}
}
